﻿ 
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ProjBackEnd.Common;
using ProjBackEnd.Common.Helper;
using ProjBackEnd.Models.AppModel.AppUserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks; 

namespace ProjBackEnd.Service
{
    public  sealed partial class AppUserService
    {
        /// <summary>
        /// APP用户登陆
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public string AppUserLogin(AppUserLoginModel model)
        {
            string conn = Function.GetConnectionString( );

            AppUserLoginResultModel resultObj = new AppUserLoginResultModel();

            try
            {
                if (model == null)
                {
                    throw new Exception("对象为空！");
                }

                if (string.IsNullOrEmpty(model.phone))
                {
                    throw new Exception("请输入手机号或手机号！");
                }

                string sql = $@"select 
                                    aua.memberid, 
                                    aua.mpno,
                                    aua.password,
                                    aua.username, 
                                    aua.userid, 
                                    aua.nickname,
                                    aua.stat, 
                                    aua.wxid 
                                from SYS_USERTB as aua 
                                where 
                                    aua.mpno ='{model.phone}'  or      aua.userid = '{model.phone}'                       
                                ";

                //获取数据
                DataSet dsInfo = SqlHelper.GetDataSet(sql, conn);
                if (dsInfo.Tables[0].Rows.Count != 1)
                {
                    throw new Exception("取用户信息出错！");
                }

                string passwd = string.IsNullOrEmpty(model.passwd) ? "" : model.passwd.Trim();

                if (dsInfo.Tables[0].Rows.Count > 0)
                {
                    string encryptPwd = SimpleCrypt.EncryptPassword(passwd);

                    if (dsInfo.Tables[0].Rows[0]["password"].ToString().Trim() != encryptPwd)
                    {
                        throw new Exception("登录密码错误！");
                    }

                    //判断用户是否禁用了
                    if (dsInfo.Tables[0].Rows[0]["stat"].ToString().Trim() == "F")
                    {
                        throw new Exception("登录失败，该账户已被禁用！");
                    }
                    resultObj.code = "0";
                    resultObj.message = "登录成功";


                    resultObj.usertp = "S";
                    resultObj.userid = dsInfo.Tables[0].Rows[0]["memberid"].ToString().Trim();
                    resultObj.usernm = dsInfo.Tables[0].Rows[0]["nickname"].ToString().Trim();
                    resultObj.openid = dsInfo.Tables[0].Rows[0]["wxid"].ToString().Trim();
                    if (!string.IsNullOrEmpty(dsInfo.Tables[0].Rows[0]["mpno"].ToString().Trim()))
                    {
                        resultObj.phone = dsInfo.Tables[0].Rows[0]["mpno"].ToString().Trim();
                    }
                    resultObj.cusname = "";
                    resultObj.taxno = "";
                    resultObj.address = "";
                    resultObj.ybnsr = "";
                    resultObj.tele = "";
                    resultObj.banknm = "";
                    resultObj.bankno = "";

                    sql = $@"select * from SYS_USERLOGIN where memberid = '{resultObj.userid}'";
                    DataSet dsLogin = SqlHelper.GetDataSet(sql, conn);
                    if (dsLogin.Tables[0].Rows.Count < 1)
                    {
                        sql = $@"insert into SYS_USERLOGIN(memberid,logindt,ostp,
                                        deviceid,token,tokenexpire,
                                        platcd,devicebrand) 
                                    values('{resultObj.userid}',getdate(),'',
                                        '','',getdate(),
                                        '','')";
                        SqlHelper.ExecuteNonQuery(conn, CommandType.Text, sql);
                    }
                    else
                    {
                        sql = $@"update SYS_USERLOGIN set logindt = getdate()
                                    where memberid = '{resultObj.userid}'";
                        SqlHelper.ExecuteNonQuery(conn, CommandType.Text, sql);
                    }
                }
                else
                {
                    throw new Exception("登录失败，未查到对应用户！");
                }


                return JsonConvert.SerializeObject(resultObj);
            }
            catch (Exception ex)
            {
                resultObj.code = "99";
                resultObj.message = ex.Message;

                return JsonConvert.SerializeObject(resultObj);
            }
        }
         
    }
}
